package com.ssm.util.test.encrypt;

import java.security.MessageDigest;

import org.apache.commons.codec.digest.DigestUtils;
/**
 * 加密算法 DigestUtils 需要引入 commons-codec.jar  常见和sha系列加密
 * @author Administrator
 *
 */
public class ShaUtil {
	
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };
	
	// sha1加密 密文16进制
		@SuppressWarnings("deprecation")
		public static String shaHex(String text, String input_charset) throws Exception {
			return DigestUtils.shaHex(getContentBytes(text, input_charset));
		}

		public static String shaHex1(String text, String input_charset) throws Exception {
			// 使用MessageDigest进行SHA1加密
			MessageDigest md_sha = MessageDigest.getInstance("SHA-1");
			md_sha.update(text.getBytes(input_charset));
			String sha1 = getFormattedText(md_sha.digest());
			return sha1;
		}

		private static byte[] getContentBytes(String content, String charset) throws Exception {
			if (charset == null || "".equals(charset)) {
				return content.getBytes();
			}
			try {
				return content.getBytes(charset);
			} catch (Exception e) {
				throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
			}
		}

		// 加密算法 把密文转成16进制的字符串形式
		public static String getFormattedText(byte[] bytes) throws Exception {
			int len = bytes.length;
			StringBuilder buf = new StringBuilder(len * 2);
			for (int j = 0; j < len; j++) {
				buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
				buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
			}
			return buf.toString();
		}

		public static void main(String[] args) throws Exception {
			String str = "123456";
			// sha1加密
			System.out.println("shaHex:" + shaHex(str, "utf-8"));
			System.out.println("shaHex:" + shaHex1(str, "utf-8"));
		}
}
